<template>
  <div>
    <el-form :model="formData" :rules="formDataRules" ref="formData">
      <h2>{{ $t("loginTypePassword.title") }}</h2>
      <span class="subtitle">{{ $t("loginTypePassword.subtitle") }}</span>
      <el-form-item label="" prop="account" class="margin-top-2">
        <el-input
          class="border-bottom"
          prefix-icon="iconfont icongerenxinxi"
          v-model="formData.account"
          :placeholder="$t('public.placeholder.account')"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="passwordVisible"
        label=""
        prop="password"
        class="margin-top-2"
      >
        <el-input
          class="border-bottom"
          prefix-icon="iconfont iconxiugaimima-01"
          v-model="formData.password"
          type="password"
          :placeholder="$t('public.placeholder.password')"
        >
          <i
            slot="suffix"
            class="iconfont iconmimabukejian"
            style="cursor: pointer"
            @click="changePasswordVisible()"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item v-else label="" prop="password" class="margin-top-2">
        <el-input
          class="border-bottom"
          prefix-icon="iconfont iconxiugaimima-01"
          v-model="formData.password"
          type="text"
          :placeholder="$t('public.placeholder.password')"
        >
          <i
            slot="suffix"
            class="iconfont iconkejian"
            style="cursor: pointer"
            @click="changePasswordVisible()"
          ></i>
        </el-input>
      </el-form-item>
      <el-row class="margin-top">
        <el-checkbox v-model="formData.autoLogin">{{
          $t("loginTypePassword.autoLogin")
        }}</el-checkbox>
        <el-link
          type="info"
          class="pull-right"
          @click="dialogForget.visible = true"
          >{{ $t("loginTypePassword.forgetPassword") }}</el-link
        >
      </el-row>
      <el-form-item class="margin-top">
        <el-button
          type="primary"
          class="form-control"
          @click="submitForm('formData')"
          >{{ $t("public.login") }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog
      :title="$t('loginTypePassword.dialogForget.title')"
      :visible.sync="dialogForget.visible"
      width="450px"
      :close-on-click-modal="dialogForget.closeOnClickModal"
      :close-on-press-escape="dialogForget.closeOnPressEscape"
      @open="openDialogForget"
      @close="closeDialogForget"
      v-loading="dialogForget.loading"
      element-loading-background="rgba(0, 0, 0, 0.5)"
    >
      <el-form
        :model="dialogForget.formData"
        :rules="dialogForget.formDataRules"
        ref="dialogForgetFormData"
      >
        <el-form-item label="" prop="telephone">
          <el-input
            class="border-bottom"
            :placeholder="$t('public.placeholder.telephone')"
            prefix-icon="iconfont iconxiugaishoujihaoma-01"
            v-model="dialogForget.formData.telephone"
            autocomplete="off"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="verifyCode" class="margin-top-2">
          <el-input
            class="border-bottom"
            :placeholder="$t('public.placeholder.verifyCode')"
            prefix-icon="iconfont iconanquanxinxi"
            v-model="dialogForget.formData.verifyCode"
            autocomplete="off"
          ></el-input>
          <el-link
            :underline="false"
            type="primary"
            class="btn-getSMS"
            @click="getSMS"
            :disabled="dialogForget.getSmsDisabled"
            >{{ btnText.getSMS }}</el-link
          >
        </el-form-item>
        <el-form-item
          v-if="dialogForget.passwordVisible"
          label=""
          prop="newPass"
          class="margin-top-2"
        >
          <el-input
            class="border-bottom"
            prefix-icon="iconfont iconxiugaimima-01"
            :placeholder="$t('public.placeholder.newPass')"
            v-model="dialogForget.formData.newPass"
            autocomplete="off"
            type="password"
          >
            <i
              slot="suffix"
              class="iconfont iconmimabukejian"
              style="cursor: pointer"
              @click="changeDialogForgetPasswordVisible()"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item v-else label="" prop="newPass" class="margin-top-2">
          <el-input
            class="border-bottom"
            prefix-icon="iconfont iconxiugaimima-01"
            :placeholder="$t('public.placeholder.newPass')"
            v-model="dialogForget.formData.newPass"
            autocomplete="off"
            type="text"
          >
            <i
              slot="suffix"
              class="iconfont iconkejian"
              style="cursor: pointer"
              @click="changeDialogForgetPasswordVisible()"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogForget.visible = false">{{
          $t("loginTypePassword.dialogForget.btnClose")
        }}</el-button>
        <el-button size="medium" type="primary" @click="submitResetPassword">{{
          $t("loginTypePassword.dialogForget.btnOk")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSms,
  toResetPassword,
  toLogin,
  loginSuccess,
  toVerifyGraph,
} from "../../api/login";
import md5 from "md5";

export default {
  name: "Password",
  props: ["loading", "operate"],
  watch: {
    operate: {
      handler(val) {
        console.log("change", val);
        if (val.type === "login") {
          this.submitForm("formData");
        }
      },
      deep: true, // 深度监听
      immediate: false, // 初次监听不执行
    },
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      let myreg = /^[1][0-9]{10}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t("public.error.telephone")));
      }
      callback();
    };
    var validatePassword = (rule, value, callback) => {
      let myreg = /^[a-z0-9A-Z]{6,16}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t("public.error.newPass")));
      }
      callback();
    };
    return {
      errorTimes: 0,
      passwordVisible: true,
      btnText: {
        getSMS: this.$t("public.getSMS"),
      },
      formData: {
        account: "",
        password: "",
        autoLogin: false,
        language: this.$i18n.locale,
      },
      formDataRules: {
        account: [
          {
            required: true,
            message: this.$t("public.error.account"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("public.error.password"),
            trigger: "blur",
          },
        ],
      },
      dialogForget: {
        loading: false,
        visible: false,
        passwordVisible: true,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        getSmsDisabled: false,
        formData: {
          telephone: "",
          verifyCode: "",
          newPass: "",
        },
        formDataRules: {
          telephone: [{ validator: validatePhone, trigger: "blur" }],
          verifyCode: [
            {
              required: true,
              message: this.$t("public.error.verifyCode"),
              trigger: "blur",
            },
          ],
          newPass: [{ validator: validatePassword, trigger: "blur" }],
        },
      },
    };
  },
  methods: {
    changePasswordVisible() {
      this.passwordVisible = !this.passwordVisible;
    },
    changeDialogForgetPasswordVisible() {
      this.dialogForget.passwordVisible = !this.dialogForget.passwordVisible;
    },
    startLoading() {
      this.$emit("loadingChange", true);
    },
    endLoading() {
      this.$emit("loadingChange", false);
    },
    getSMS() {
      let _this = this;
      _this.$refs["dialogForgetFormData"].validateField(
        "telephone",
        (error) => {
          if (error.length == 0) {
            let captcha = new TencentCaptcha("2082855902", function (res) {
              if (res.ret === 0) {
                // 防水墙验证前端成功
                toVerifyGraph({
                  // ipAddr: "string",
                  randstr: res.randstr,
                  ticket: res.ticket,
                }).then((res) => {
                  if (res.status === 200) {
                    getSms({
                      telephone: _this.dialogForget.formData.telephone,
                      smsType: "FORGET_PASS",
                    }).then((res) => {
                      if (res.status === 200) {
                        _this.$message.success(
                          _this.errorCode[_this.$i18n.locale][res.message]
                        );
                        let s = 59,
                          text = _this.$t("public.text");
                        _this.btnText.getSMS = `${s} ${text}`;
                        let timer = setInterval(function () {
                          s--;
                          if (s <= 0) {
                            clearInterval(timer);
                            _this.btnText.getSMS = _this.$t("public.getSMS");
                            _this.dialogForget.getSmsDisabled = false;
                          } else {
                            _this.btnText.getSMS = `${s} ${text}`;
                            _this.dialogForget.getSmsDisabled = true;
                          }
                        }, 1000);
                      } else {
                        _this.$message.error(
                          _this.errorCode[_this.$i18n.locale][res.message]
                        );
                      }
                    });
                  } else {
                    _this.$message.error(
                      _this.errorCode[_this.$i18n.locale][res.message]
                    );
                  }
                });
              }
            });
            captcha.show(); // 启动防水墙
          } else {
            this.$message({
              message: this.$t("public.error.telephone"),
              type: "warning",
            });
            return false;
          }
        }
      );
    },
    submitForm(formName) {
      let _this = this;
      _this.$refs[formName].validate((valid) => {
        if (valid) {
          if (_this.errorTimes > 2) {
            let captcha = new TencentCaptcha("2082855902", function (res) {
              if (res.ret === 0) {
                // 防水墙验证前端成功
                toVerifyGraph({
                  // ipAddr: "string",
                  randstr: res.randstr,
                  ticket: res.ticket,
                }).then((res) => {
                  if (res.status === 200) {
                    _this.actionLogin(_this.formData)
                  } else {
                    _this.$message.error(
                      _this.errorCode[_this.$i18n.locale][res.message]
                    );
                  }
                });
              }
            });
            captcha.show(); // 启动防水墙
          } else {
            _this.actionLogin(_this.formData)
          }
        } else {
          return false;
        }
      });
    },
    actionLogin(formData) {
      let params = Object.assign({},formData)
      if (params.password.length != 32) {
        params.password = md5(params.password);
      }
      toLogin(params).then((res) => {
        if (res.status === 200) {
          this.$message.success(
            this.errorCode[this.$i18n.locale][res.message]
          );
          if (formData.autoLogin) {
            localStorage.setItem(
              "loginInfo",
              JSON.stringify({
                account: params.account,
                password: params.password,
                time: new Date().getTime(),
              })
            );
          } else {
            localStorage.removeItem("loginInfo");
          }
          loginSuccess(res.data);
        } else {
          this.errorTimes++;
          this.$message.error(
            this.errorCode[this.$i18n.locale][res.message]
          );
        }
      });
    },
    submitResetPassword() {
      this.$refs["dialogForgetFormData"].validate((valid) => {
        if (valid) {
          let params = {
            telephone: this.dialogForget.formData.telephone,
            verifyCode: this.dialogForget.formData.verifyCode,
            newPass: md5(this.dialogForget.formData.newPass),
          };
          toResetPassword(params).then((res) => {
            if (res.status === 200) {
              this.$message.success(
                this.errorCode[this.$i18n.locale][res.message]
              );
              this.dialogForget.visible = false;
            } else {
              this.$message.error(
                this.errorCode[this.$i18n.locale][res.message]
              );
            }
          });
        } else {
          return false;
        }
      });
    },
    openDialogForget() {},
    closeDialogForget() {
      this.$refs["dialogForgetFormData"].resetFields();
      this.dialogForget.passwordVisible = true;
    },
  },
  created() {
    if (window.TencentCaptcha === undefined) {
      let script = document.createElement("script");
      let head = document.getElementsByTagName("head")[0];
      script.type = "text/javascript";
      script.charset = "UTF-8";
      script.src = "https://ssl.captcha.qq.com/TCaptcha.js";
      head.appendChild(script);
    }
    // 自动填入密码
    let loginInfo = localStorage.getItem("loginInfo");
    if (loginInfo) {
      try {
        loginInfo = JSON.parse(loginInfo);
        console.info(loginInfo);
        let now = new Date().getTime();
        if (loginInfo.time && now - loginInfo.time < 432000000) {
          this.formData.account = loginInfo.account || "";
          this.formData.password = loginInfo.password || "";
        } else {
          localStorage.removeItem("loginInfo");
        }
      } catch (e) {
        console.info(e);
      }
    }
  },
};
</script>